package com.zjp.aop.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;


public class CommonAspect {

    // 匹配注解
    @Pointcut("@annotation(com.zjp.aop.annotation.Log)")
    public void t1PointCut() {

    }

    // 任何的public方法
    @Pointcut("execution(public * *(..))")
    public void t2PointCut() {

    }

    // 以set开始的方法
    @Pointcut("execution(* set*(..))")
    public void t3PointCut() {

    }


    @Before("t1PointCut()")
    public void test() {

    }

    // 方法参数
    @Pointcut("args(java.lang.String)")
    public void pointCutArgs() {


    }


    @After("t1PointCut()")
    public void after() {

    }


    public <T extends Annotation> T getAnnotation(JoinPoint joinPoint, Class<T> annotationClass) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(annotationClass);
        }
        return null;
    }


    public Method getMethod(JoinPoint joinPoint) throws NoSuchMethodException {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        return joinPoint.getTarget().getClass().getMethod(method.getName(), method.getParameterTypes());
    }
}
